package com.ywf.corebase.framework.handler;

import com.ywf.corebase.common.utils.RequestContextUtil;
import com.ywf.corebase.framework.annotation.ResponseResult;
import com.ywf.corebase.framework.interceptor.ResponseResultInterceptor;
import com.ywf.corebase.framework.result.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * ClassName:ResponseResultHandler
 * Package:com.ywf.myproject.common.handler
 * Description:
 *
 * @Date:2021/3/3 6:51
 * @Author:YWF
 */
@ControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {

    final static Logger logger = LoggerFactory.getLogger(ResponseResultHandler.class);

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        logger.info("返回参数统一处理{}001");
        HttpServletRequest request = RequestContextUtil.getRequest();
        ResponseResult responseResult = (ResponseResult) request.getAttribute(ResponseResultInterceptor.RESPONSE_RESULT_ANN);
        return responseResult!=null?true:false;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        logger.info("返回参数之前处理{}002"+body);
        ResponseResult responseResultAnn = (ResponseResult) RequestContextUtil.getRequest().getAttribute(ResponseResultInterceptor.RESPONSE_RESULT_ANN);
        Class<? extends R> resultClazz = responseResultAnn.value();
        logger.info("注解值："+resultClazz.toString());
        if (resultClazz.isAssignableFrom(R.class)){
            if (body instanceof R){
                R r = (R) body;
                logger.info("返回结果："+r);
                logger.info("错误："+r.getMsg());
                return R.ok().code(r.getCode()).message(r.getMsg());
            }else if (body instanceof String){
                return R.ok().data(body);
            }
            return R.ok().data(body);
        }
        return body;
    }

}
